package cn.lbd;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class CuratorUpdate {
    private final String SOCKET_ADDRESS = "39.97.191.1:2181";
    CuratorFramework client;

    @Before
    public void init() {
        client = CuratorFrameworkFactory.builder()
                .connectString(SOCKET_ADDRESS)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("create_new")
                .build();

        client.start();
        System.out.println(client.isStarted());
    }

    @After
    public void destroy() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        client.setData()
                .forPath("/demo1", "demo1_update".getBytes());
        System.out.println("结束");
    }

    @Test
    public void test2() throws Exception {
        client.setData()
                //有异步回调的情况下会导致乐观锁失败？
                .withVersion(3)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getPath());
                        System.out.println(curatorEvent.getType());
                    }
                })
                .forPath("/demo1", "demo1_update3".getBytes());
        TimeUnit.SECONDS.sleep(3);
        System.out.println("结束");
    }

    @Test
    public void test3() throws Exception {
        client.setData()
                .withVersion(3)
                .forPath("/demo1", "demo1_update2".getBytes());
        System.out.println("结束");
    }
}
